//
//  CQAFNetHelper.m
//  CQFramework
//
//  Created by runo on 16/5/27.
//  Copyright © 2016年 caoqin. All rights reserved.
//

#import "CQAFNetHelper.h"
#import "AFNetworking.h"
#import "CQURL.h"
@interface CQAFNetHelper ()

@property(nonatomic,strong) AFHTTPSessionManager *manager;
@property(nonatomic,strong) NSMutableArray *tasks;

@end

@implementation CQAFNetHelper

-(NSMutableArray *)tasks{
    if (_tasks == nil) {
        _tasks = [[NSMutableArray alloc]init];
    }
    return _tasks;
}

+(instancetype)sharInstance{
    
    static CQAFNetHelper *helper = nil;
    static dispatch_once_t token;
    dispatch_once(&token, ^{
        helper = [[CQAFNetHelper alloc]init];
        helper.manager = [[AFHTTPSessionManager alloc]init];
    });
    return helper;
}

-(NSURLSessionDataTask *)cqPostparams:(NSDictionary *)dic CompletionBlock:(RBlock)block{
    
    //请求超时
    [self.manager.requestSerializer willChangeValueForKey:@"timeoutInterval"];
    self.manager.requestSerializer.timeoutInterval = 30.f;
    [self.manager.requestSerializer didChangeValueForKey:@"timeoutInterval"];
    self.manager.responseSerializer = [[AFCompoundResponseSerializer alloc] init];
    self.Mblock = block;
    
    NSURLSessionDataTask *task = [self.manager POST:[CQURL getPostURL] parameters:dic progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSDictionary * dics=[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        NSLog(@"%@",dics[@"Message"]);
        responseResult * result=[[responseResult alloc] initWithResult:dics isCorrect:YES];
        self.Mblock(result);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        responseResult * result=[[responseResult alloc] initWithResult:nil isCorrect:NO];
        NSLog(@"%@",error);
        self.Mblock(result);
        
    }];
    
    if (task != nil) {
     [self.tasks addObject:task];
    }
    return task;
    
}

-(void)cqCloseAllTask{
    
    for (NSURLSessionDataTask *task in self.tasks) {
        [task cancel];
    }
}

-(void)cqCloseTisTask:(NSURLSessionDataTask *)task{
    [task cancel];
}

@end
